﻿using AduSkin.Controls;
using AduSkin.Controls.Metro;
using DBMC_Core;
using Newtonsoft.Json;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;

namespace DBMC
{
    /// <summary>
    /// User.xaml 的交互逻辑
    /// </summary>
    public partial class User : Window
    {
        private bool isDragging;
        private Point startPoint;
        public ObservableCollection<UserInfo> Users { get; set; }
        public Minecraft minecraft = new Minecraft();
        public TokenGenerator tokenGenerator = new TokenGenerator();
        LauncherCore launcherCore = new LauncherCore();

        public User()
        {
            InitializeComponent();

            LoadUsers(); // 加载用户信息
        }

        public void LoadUsers()
        {
            LauncherCore.WriteLog($"启动器核心：账号管理 - 窗口打开正常");
            if (launcherCore.ConfigFileExists)
            {
                LauncherCore.WriteLog($"启动器核心：账号管理 - 获取本地已存储账号中...");
                string jsonData = File.ReadAllText(launcherCore.ConfigFile);
                RootObject dbmcData = JsonConvert.DeserializeObject<RootObject>(jsonData);
                if (dbmcData?.Account != null)
                {
                    Users = new ObservableCollection<UserInfo>(dbmcData.Account);
                    lstUsers.ItemsSource = Users;
                    LauncherCore.WriteLog($"启动器核心：账号管理 - 获取本地已存储账号成功");
                }
                else
                {
                    LauncherCore.WriteLog($"启动器核心：账号管理 - 获取本地已存储账号失败，因为还未添加账号");
                }
            }
        }

        public void SaveUsers()
        {
            if (launcherCore.ConfigFileExists)
            {
                LauncherCore.WriteLog($"启动器核心：账号管理 - 刷新账号信息中...");
                string jsonData = File.ReadAllText(launcherCore.ConfigFile);
                RootObject dbmcData = JsonConvert.DeserializeObject<RootObject>(jsonData);
                // 确保 dbmcData.Account 也是 ObservableCollection<UserInfo> 类型
                dbmcData.Account = new ObservableCollection<UserInfo>(Users);
                string updatedJsonData = JsonConvert.SerializeObject(dbmcData, Formatting.Indented);
                File.WriteAllText(launcherCore.ConfigFile, updatedJsonData);
                LauncherCore.WriteLog($"启动器核心：账号管理 - 刷新账号信息成功");
            }
        }

        public void AddUser_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            if (button.ContextMenu != null)
            {
                button.ContextMenu.PlacementTarget = button;
                button.ContextMenu.IsOpen = true;
            }
        }

        public void DeleteItem(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            // 这里应该使用 UserInfo 类型
            if (button.CommandParameter is UserInfo userToRemove)
            {
                LauncherCore.WriteLog($"启动器核心：账号管理 - 用户点击了“删除账号”");
                Users.Remove(userToRemove);
                LauncherCore.WriteLog($"启动器核心：账号管理 - {userToRemove.Name} 账号已删除");
                SaveUsers(); // 保存用户信息
                NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                {
                    Title = "账号管理",
                    Content = $"{userToRemove.Name} - 账号删除成功",
                    NotificationType = EnumPromptType.Success
                });
            }

        }

        private void UseUser_Click(object sender, RoutedEventArgs e)
        {
            SaveUsers();
            DialogResult = true;
            Close();
        }

        private void local_Click(object sender, RoutedEventArgs e)
        {
            LauncherCore.WriteLog($"启动器核心：账号管理 - 用户点击了“添加账号”中的“离线账号”");
            AddLocalUser addLocalUser = new AddLocalUser();
            bool? res = addLocalUser.ShowDialog();
            if (res == true)
            {
                if (string.IsNullOrWhiteSpace(addLocalUser.PlayerName))
                {
                    LauncherCore.WriteLog($"启动器核心：账号管理 - 添加离线账号失败，因为用户名为空");
                    NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                    {
                        Title = "账号管理",
                        Content = "类型：离线账号\n事件：用户名为空",
                        NotificationType = EnumPromptType.Error
                    });
                    return;
                }

                // 查找是否已有相同名称的用户
                var existingUser = Users.FirstOrDefault(u => u.Name.Equals(addLocalUser.PlayerName, StringComparison.OrdinalIgnoreCase));
                if (existingUser != null)
                {
                    if (existingUser.Isfixed == Visibility.Hidden)
                    {
                        LauncherCore.WriteLog($"启动器核心：账号管理 - 添加离线账号失败，因为当前 {existingUser.Name} 账号不可更改");
                        NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                        {
                            Title = "账号管理",
                            Content = $"类型：离线账号\n名称：{existingUser.Name}\n事件：当前账户不可更改",
                            NotificationType = EnumPromptType.Error
                        });
                        return;
                    }
                    else
                    {
                        if (AduMessageBox.Show("用户已经存，在是否覆盖信息？", "警告", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                        {
                            existingUser.UUID = addLocalUser.UUID; // 更新UUID
                            existingUser.Access_Token = tokenGenerator.SetToken; // 更新Access Token
                            existingUser.Type = "local";
                            existingUser.Time = launcherCore.GenerateTimeStamp;
                            LauncherCore.WriteLog($"启动器核心：账号管理 - 刷新 {existingUser.Name} 账号信息成功");
                            NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                            {
                                Title = "账号管理",
                                Content = $"类型：离线账号\n名称：{addLocalUser.PlayerName}\n事件：账户信息已更新",
                                NotificationType = EnumPromptType.Success
                            });
                        }
                    }

                }
                else
                {
                    // 如果没有找到，添加新用户
                    UserInfo newUser = new UserInfo
                    {
                        Name = addLocalUser.PlayerName,
                        UUID = addLocalUser.UUID,
                        Type = "local",
                        Access_Token = tokenGenerator.SetToken,
                        Time = launcherCore.GenerateTimeStamp
                    };
                    Users.Add(newUser);
                    LauncherCore.WriteLog($"启动器核心：账号管理 - 添加离线账号成功：{addLocalUser.PlayerName} - {addLocalUser.UUID}");
                    NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                    {
                        Title = "账号管理",
                        Content = $"类型：离线账号\n名称：{addLocalUser.PlayerName}\n事件：添加成功",
                        NotificationType = EnumPromptType.Success
                    });
                }
                SaveUsers();
            }
        }

        private void msa_Click(object sender, RoutedEventArgs e)
        {
            LauncherCore.WriteLog($"启动器核心：账号管理 - 用户点击了“添加账号”中的“微软账号”");
            AddMsaUser addMsaUser = new AddMsaUser
            {
                Topmost = true
            };
            bool? res = addMsaUser.ShowDialog();
            if (res == true)
            {
                UserInfo existingUser = Users.FirstOrDefault(u => u.Name.Equals(addMsaUser.PlayerName, StringComparison.OrdinalIgnoreCase));
                if (existingUser != null)
                {
                    if (existingUser.Isfixed == Visibility.Hidden)
                    {
                        LauncherCore.WriteLog($"启动器核心：账号管理 - 添加微软账号失败，因为当前 {existingUser.Name} 账号不可更改");
                        NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                        {
                            Title = "账号管理",
                            Content = $"类型：微软账号\n名称：{existingUser.Name}\n事件：当前账户不可更改",
                            NotificationType = EnumPromptType.Error
                        });
                        return;
                    }
                    else
                    {
                        // 如果找到，更新该用户的信息
                        existingUser.UUID = addMsaUser.UUID; // 更新UUID
                        existingUser.Access_Token = addMsaUser.Access_Token; // 更新Access Token
                        existingUser.Refresh_Token = addMsaUser.Refresh_Token;
                        existingUser.Type = "msa";
                        existingUser.Time = launcherCore.GenerateTimeStamp;
                        LauncherCore.WriteLog($"启动器核心：账号管理 - 刷新 {existingUser.Name} 账号信息成功");
                        NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                        {
                            Title = "账号管理",
                            Content = $"类型：微软账号\n名称：{addMsaUser.PlayerName}\n事件：账户信息已刷新",
                            NotificationType = EnumPromptType.Success
                        });
                    }
                }
                else
                {
                    UserInfo newUser = new UserInfo
                    {
                        Name = addMsaUser.PlayerName,
                        UUID = addMsaUser.UUID,
                        Type = "msa",
                        Access_Token = addMsaUser.Access_Token,
                        Refresh_Token = addMsaUser.Refresh_Token,
                        Time = launcherCore.GenerateTimeStamp
                    };
                    Users.Add(newUser);
                    LauncherCore.WriteLog($"启动器核心：账号管理 - 添加微软账号成功：{addMsaUser.PlayerName} - {addMsaUser.UUID}");
                    NoticeManager.NotificationShow.AddNotification(new NotificationModel()
                    {
                        Title = "账号管理",
                        Content = $"类型：微软账号\n名称：{addMsaUser.PlayerName}\n事件：添加成功",
                        NotificationType = EnumPromptType.Success
                    });
                }
                SaveUsers();
            }
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            isDragging = true;
            startPoint = e.GetPosition(this);
        }

        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                Point currentPoint = e.GetPosition(this);
                this.Left += currentPoint.X - startPoint.X;
                this.Top += currentPoint.Y - startPoint.Y;
            }
        }

        private void Window_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            isDragging = false;
        }

        private void ExitApp_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}


public class RootObject : INotifyPropertyChanged
{
    private int useJavaOptions;
    private string javaPath;
    private int useMemory;
    private bool startTopmost;
    private bool startTools;
    private bool gameTips;
    private ObservableCollection<UserInfo> account;

    public string JavaPath
    {
        get => javaPath;
        set
        {
            javaPath = value;
            OnPropertyChanged(nameof(JavaPath));
        }
    }

    public int UseJavaOptions
    {
        get => useJavaOptions;
        set
        {
            useJavaOptions = value;
            OnPropertyChanged(nameof(UseJavaOptions));
        }
    }

    public int UseMemory
    {
        get => useMemory;
        set
        {
            useMemory = value;
            OnPropertyChanged(nameof(UseMemory));
        }
    }

    public bool StartTopmost
    {
        get => startTopmost;
        set
        {
            startTopmost = value;
            OnPropertyChanged(nameof(StartTopmost));
        }
    }

    public bool StartTools
    {
        get => startTools;
        set
        {
            startTools = value;
            OnPropertyChanged(nameof(StartTools));
        }
    }

    public bool GameTips
    {
        get => gameTips;
        set
        {
            gameTips = value;
            OnPropertyChanged(nameof(GameTips));
        }
    }

    public ObservableCollection<UserInfo> Account
    {
        get => account;
        set
        {
            account = value;
            OnPropertyChanged(nameof(Account));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class UserInfo : INotifyPropertyChanged
{
    private string name;
    private string uuid;
    private string type;
    private string access_token;
    private string refresh_token;
    private Visibility isfixed;
    private bool isSelected;
    private long time;

    public string Name
    {
        get { return name; }
        set { name = value; OnPropertyChanged("Name"); }
    }
    public string UUID
    {
        get { return uuid; }
        set { uuid = value; OnPropertyChanged("UUID"); }
    }
    public string Type
    {
        get => type;
        set
        {
            if (type != value)
            {
                type = value;
                OnPropertyChanged("Type");
                OnPropertyChanged("DisplayType"); // 当Type变化时，也需要通知DisplayType变化
            }
        }
    }
    public string Access_Token
    {
        get { return access_token; }
        set { access_token = value; OnPropertyChanged("Access_Token"); }
    }
    public string Refresh_Token
    {
        get { return refresh_token; }
        set { refresh_token = value; OnPropertyChanged("Refresh_Token"); }
    }
    public Visibility Isfixed
    {
        get { return isfixed; }
        set { isfixed = value; OnPropertyChanged("Isfixed"); }
    }
    public bool IsSelected
    {
        get { return isSelected; }
        set { isSelected = value; OnPropertyChanged("IsSelected"); }
    }
    public long Time
    {
        get { return time; }
        set { time = value; OnPropertyChanged("Time"); }
    }

    public BitmapImage Image
    {
        get
        {
            // 文件缓存目录
            string cacheDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Temp", "DBMC", "MCImageCache");
            string cacheFile = Path.Combine(cacheDir, $"{name}.png");


            // 检查缓存是否存在且有效
            if (File.Exists(cacheFile) && (DateTime.Now - File.GetLastWriteTime(cacheFile)).TotalDays < 1)
            {
                // 从本地缓存加载图像
                return new BitmapImage(new Uri(cacheFile));
            }
            else
            {
                // 尝试从网络加载图像
                BitmapImage image = new BitmapImage();

                try
                {
                    image.BeginInit();
                    image.UriSource = new Uri("https://mineskin.eu/helm/" + $"{name}" + "/100.png", UriKind.Absolute);
                    image.CacheOption = BitmapCacheOption.OnLoad; // 设置缓存选项
                    image.DownloadCompleted += (s, e) =>
                    {
                        // 图像下载成功，保存到本地缓存
                        SaveImageToCache(image, cacheDir, cacheFile);
                    };
                    image.DownloadFailed += (s, e) =>
                    {
                        // 如果下载失败，使用默认的Base64编码的图像
                        image = DecodeImageFromBase64(Danbai.HandImage);
                    };
                    image.EndInit();
                    return image;
                }
                catch
                {
                    // 如果在初始化图像期间发生异常，使用Base64默认图像
                    image = DecodeImageFromBase64(Danbai.HandImage);
                    return image;
                }
            }
        }
    }

    private BitmapImage DecodeImageFromBase64(string base64String)
    {
        BitmapImage image = new BitmapImage();
        if (!string.IsNullOrEmpty(base64String))
        {
            byte[] imageBytes = Convert.FromBase64String(base64String);
            using (MemoryStream memStream = new MemoryStream(imageBytes))
            {
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.StreamSource = memStream;
                image.EndInit();
                image.Freeze(); // 因为是在非UI线程使用UI资源，所以进行冻结
            }
        }
        return image;
    }

    // 保存图像到本地缓存
    private void SaveImageToCache(BitmapSource image, string cacheDir, string cacheFile)
    {
        if (!Directory.Exists(cacheDir))
        {
            Directory.CreateDirectory(cacheDir);
        }

        using (var fileStream = new FileStream(cacheFile, FileMode.Create))
        {
            BitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(image));
            encoder.Save(fileStream);
        }
    }

    public string DisplayType
    {
        get
        {
            switch (Type)
            {
                case "msa":
                    return "微软登录";
                case "local":
                    return "离线登录";
                default:
                    return Type; // 或者返回一个默认字符串，例如"未知类型"
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}